/**
 * Copilot Store
 * 管理AI Copilot的状态、建议、检查清单、对话历史
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

/**
 * 建议类型
 */
export type SuggestionType =
  | 'add_example'      // 添加例子
  | 'add_data'         // 添加数据
  | 'add_transition'   // 添加过渡句
  | 'explain_concept'  // 解释概念
  | 'summarize'        // 总结上文
  | 'expand'           // 扩展内容
  | 'fix_logic'        // 修复逻辑
  | 'improve_style';   // 改进文风

/**
 * 建议优先级
 */
export type SuggestionPriority = 'high' | 'medium' | 'low';

/**
 * 写作意图
 */
export type WritingIntent =
  | 'argument'      // 论述
  | 'example'       // 举例
  | 'summary'       // 总结
  | 'transition'    // 过渡
  | 'introduction'  // 介绍
  | 'conclusion';   // 结论

/**
 * Copilot触发模式
 */
export type CopilotMode = 'active' | 'moderate' | 'passive';

/**
 * Copilot风格
 */
export type CopilotStyle = 'professional' | 'friendly' | 'concise';

/**
 * 建议接口
 */
export interface Suggestion {
  id: string;
  type: SuggestionType;
  title: string;
  description: string;
  priority: SuggestionPriority;
  targetPosition: number;       // 建议应用的位置
  targetText?: string;           // 建议应用的目标文本
  actionText: string;            // 按钮文字
  icon?: string;
  timestamp: number;
}

/**
 * 检查清单项
 */
export interface ChecklistItem {
  id: string;
  title: string;
  description: string;
  status: 'passed' | 'warning' | 'failed' | 'pending';
  position?: number;             // 问题位置
  suggestion?: string;           // 改进建议
  category: 'structure' | 'content' | 'style' | 'grammar';
}

/**
 * 参考资料
 */
export interface Reference {
  id: string;
  title: string;
  summary: string;
  source: string;
  url?: string;
  credibility: number;           // 0-100
  relevance: number;             // 0-100
  timestamp: number;
}

/**
 * 聊天消息
 */
export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
  canInsert?: boolean;           // 是否可以插入到文章
}

/**
 * 自动补全选项
 */
export interface AutocompleteOption {
  id: string;
  text: string;
  confidence: number;            // 0-1
  type: 'word' | 'sentence' | 'paragraph';
}

/**
 * Copilot设置
 */
export interface CopilotSettings {
  mode: CopilotMode;
  style: CopilotStyle;
  autocompleteDelay: number;     // 毫秒
  enableAutocomplete: boolean;
  enableSuggestions: boolean;
  enableChecklist: boolean;
  enableChat: boolean;
  enableReferences: boolean;
}

/**
 * 上下文信息
 */
export interface EditorContext {
  currentText: string;
  selectedText: string;
  cursorPosition: number;
  previousParagraphs: string[];
  nextParagraphs: string[];
  wordCount: number;
  intent?: WritingIntent;
}

export interface CopilotState {
  // 建议
  suggestions: Suggestion[];
  quickActions: Suggestion[];    // 快速操作卡片（3-5个）

  // 检查清单
  checklist: ChecklistItem[];
  checklistProgress: number;     // 0-100

  // 参考资料
  references: Reference[];

  // 聊天
  chatHistory: ChatMessage[];
  chatLoading: boolean;

  // 自动补全
  autocompleteOptions: AutocompleteOption[];
  showAutocomplete: boolean;

  // 上下文
  currentContext: EditorContext | null;
  detectedIntent: WritingIntent | null;

  // 设置
  settings: CopilotSettings;

  // UI状态
  isPanelVisible: boolean;
  isPanelCollapsed: boolean;
  panelWidth: number;            // px

  // Actions
  fetchSuggestions: (context: EditorContext) => Promise<void>;
  addSuggestion: (suggestion: Suggestion) => void;
  removeSuggestion: (id: string) => void;
  applySuggestion: (id: string) => Promise<void>;

  updateChecklist: (context: EditorContext) => Promise<void>;
  updateChecklistItem: (id: string, status: ChecklistItem['status']) => void;

  fetchReferences: (query: string) => Promise<void>;
  citeReference: (id: string) => void;

  sendChatMessage: (message: string) => Promise<void>;
  insertChatResponse: (messageId: string) => void;
  clearChatHistory: () => void;

  fetchAutocomplete: (context: EditorContext) => Promise<void>;
  acceptAutocomplete: (optionId: string) => void;
  dismissAutocomplete: () => void;

  detectIntent: (context: EditorContext) => WritingIntent | null;
  analyzeProblems: (context: EditorContext) => Promise<void>;

  updateSettings: (settings: Partial<CopilotSettings>) => void;
  togglePanel: () => void;
  setPanelWidth: (width: number) => void;

  clearAll: () => void;
}

const DEFAULT_SETTINGS: CopilotSettings = {
  mode: 'moderate',
  style: 'friendly',
  autocompleteDelay: 1000,
  enableAutocomplete: true,
  enableSuggestions: true,
  enableChecklist: true,
  enableChat: true,
  enableReferences: true,
};

export const useCopilotStore = create<CopilotState>()(
  persist(
    (set, get) => ({
      suggestions: [],
      quickActions: [],

      checklist: [],
      checklistProgress: 0,

      references: [],

      chatHistory: [],
      chatLoading: false,

      autocompleteOptions: [],
      showAutocomplete: false,

      currentContext: null,
      detectedIntent: null,

      settings: DEFAULT_SETTINGS,

      isPanelVisible: true,
      isPanelCollapsed: false,
      panelWidth: 320,

      /**
       * 获取写作建议
       */
      fetchSuggestions: async (context) => {
        console.log('🤖 [Copilot] Fetching suggestions...');

        set({ currentContext: context });

        // 检测写作意图
        const intent = get().detectIntent(context);
        set({ detectedIntent: intent });

        try {
          // TODO: 调用API获取建议
          // const response = await copilotAIService.getSuggestions(context, intent);

          // Mock建议
          const mockSuggestions = get().generateMockSuggestions(context, intent);
          set({
            suggestions: mockSuggestions,
            quickActions: mockSuggestions.slice(0, 5), // 前5个作为快速操作
          });

          console.log('✅ [Copilot] Got', mockSuggestions.length, 'suggestions');
        } catch (error) {
          console.error('❌ [Copilot] Failed to fetch suggestions:', error);
        }
      },

      /**
       * 添加建议
       */
      addSuggestion: (suggestion) => {
        set((state) => ({
          suggestions: [...state.suggestions, suggestion],
        }));
      },

      /**
       * 移除建议
       */
      removeSuggestion: (id) => {
        set((state) => ({
          suggestions: state.suggestions.filter((s) => s.id !== id),
          quickActions: state.quickActions.filter((s) => s.id !== id),
        }));
      },

      /**
       * 应用建议
       */
      applySuggestion: async (id) => {
        const suggestion = get().suggestions.find((s) => s.id === id);
        if (!suggestion) return;

        console.log('✨ [Copilot] Applying suggestion:', suggestion.title);

        try {
          // TODO: 执行对应的AI操作
          // await editorAIService.executeOperation(...)

          // 移除已应用的建议
          get().removeSuggestion(id);

          console.log('✅ [Copilot] Suggestion applied');
        } catch (error) {
          console.error('❌ [Copilot] Failed to apply suggestion:', error);
        }
      },

      /**
       * 更新检查清单
       */
      updateChecklist: async (context) => {
        console.log('📋 [Copilot] Updating checklist...');

        try {
          // TODO: 调用API分析文章质量
          // const response = await copilotAIService.checkQuality(context);

          // Mock检查清单
          const mockChecklist = get().generateMockChecklist(context);
          const passedCount = mockChecklist.filter((item) => item.status === 'passed').length;
          const progress = Math.round((passedCount / mockChecklist.length) * 100);

          set({
            checklist: mockChecklist,
            checklistProgress: progress,
          });

          console.log('✅ [Copilot] Checklist updated, progress:', progress + '%');
        } catch (error) {
          console.error('❌ [Copilot] Failed to update checklist:', error);
        }
      },

      /**
       * 更新检查清单项
       */
      updateChecklistItem: (id, status) => {
        set((state) => ({
          checklist: state.checklist.map((item) =>
            item.id === id ? { ...item, status } : item
          ),
        }));
      },

      /**
       * 获取参考资料
       */
      fetchReferences: async (query) => {
        console.log('📚 [Copilot] Fetching references for:', query);

        try {
          // TODO: 调用API搜索参考资料
          // const response = await copilotAIService.searchReferences(query);

          // Mock参考资料
          const mockReferences = get().generateMockReferences(query);
          set({ references: mockReferences });

          console.log('✅ [Copilot] Got', mockReferences.length, 'references');
        } catch (error) {
          console.error('❌ [Copilot] Failed to fetch references:', error);
        }
      },

      /**
       * 引用参考资料
       */
      citeReference: (id) => {
        const reference = get().references.find((r) => r.id === id);
        if (!reference) return;

        console.log('📌 [Copilot] Citing reference:', reference.title);
        // TODO: 将引用插入到编辑器
      },

      /**
       * 发送聊天消息
       */
      sendChatMessage: async (message) => {
        const userMessage: ChatMessage = {
          id: `user_${Date.now()}`,
          role: 'user',
          content: message,
          timestamp: Date.now(),
        };

        set((state) => ({
          chatHistory: [...state.chatHistory, userMessage],
          chatLoading: true,
        }));

        console.log('💬 [Copilot] Sending message:', message);

        try {
          // TODO: 调用API获取回复
          // const response = await copilotAIService.chat(message, get().currentContext);

          // Mock回复
          await new Promise((resolve) => setTimeout(resolve, 1000));
          const reply = get().generateMockChatReply(message);

          const assistantMessage: ChatMessage = {
            id: `assistant_${Date.now()}`,
            role: 'assistant',
            content: reply,
            timestamp: Date.now(),
            canInsert: true,
          };

          set((state) => ({
            chatHistory: [...state.chatHistory, assistantMessage],
            chatLoading: false,
          }));

          console.log('✅ [Copilot] Got reply');
        } catch (error) {
          console.error('❌ [Copilot] Failed to get reply:', error);
          set({ chatLoading: false });
        }
      },

      /**
       * 插入聊天回复到文章
       */
      insertChatResponse: (messageId) => {
        const message = get().chatHistory.find((m) => m.id === messageId);
        if (!message || message.role !== 'assistant') return;

        console.log('📝 [Copilot] Inserting chat response to editor');
        // TODO: 插入到编辑器
      },

      /**
       * 清空聊天历史
       */
      clearChatHistory: () => {
        set({ chatHistory: [] });
      },

      /**
       * 获取自动补全建议
       */
      fetchAutocomplete: async (context) => {
        if (!get().settings.enableAutocomplete) return;

        console.log('⌨️ [Copilot] Fetching autocomplete...');

        try {
          // TODO: 调用API获取补全建议
          // const response = await copilotAIService.autocomplete(context);

          // Mock补全建议
          const mockOptions = get().generateMockAutocomplete(context);
          set({
            autocompleteOptions: mockOptions,
            showAutocomplete: mockOptions.length > 0,
          });

          console.log('✅ [Copilot] Got', mockOptions.length, 'autocomplete options');
        } catch (error) {
          console.error('❌ [Copilot] Failed to fetch autocomplete:', error);
        }
      },

      /**
       * 接受自动补全
       */
      acceptAutocomplete: (optionId) => {
        const option = get().autocompleteOptions.find((o) => o.id === optionId);
        if (!option) return;

        console.log('✨ [Copilot] Accepting autocomplete:', option.text);
        // TODO: 插入到编辑器

        set({
          autocompleteOptions: [],
          showAutocomplete: false,
        });
      },

      /**
       * 关闭自动补全
       */
      dismissAutocomplete: () => {
        set({
          autocompleteOptions: [],
          showAutocomplete: false,
        });
      },

      /**
       * 检测写作意图
       */
      detectIntent: (context) => {
        const text = context.currentText.toLowerCase();
        const wordCount = context.wordCount;

        // 简单的意图检测逻辑
        if (text.includes('例如') || text.includes('比如') || text.includes('举个例子')) {
          return 'example';
        }
        if (text.includes('总之') || text.includes('综上') || text.includes('总结')) {
          return 'summary';
        }
        if (text.includes('首先') || text.includes('其次') || text.includes('另外')) {
          return 'transition';
        }
        if (wordCount < 100) {
          return 'introduction';
        }
        if (context.nextParagraphs.length === 0) {
          return 'conclusion';
        }

        return 'argument';
      },

      /**
       * 分析写作问题
       */
      analyzeProblems: async (context) => {
        console.log('🔍 [Copilot] Analyzing problems...');

        try {
          // TODO: 调用API分析问题
          // const response = await copilotAIService.analyzeProblems(context);

          console.log('✅ [Copilot] Analysis complete');
        } catch (error) {
          console.error('❌ [Copilot] Failed to analyze problems:', error);
        }
      },

      /**
       * 更新设置
       */
      updateSettings: (newSettings) => {
        set((state) => ({
          settings: { ...state.settings, ...newSettings },
        }));
      },

      /**
       * 切换面板显示
       */
      togglePanel: () => {
        set((state) => ({
          isPanelVisible: !state.isPanelVisible,
        }));
      },

      /**
       * 设置面板宽度
       */
      setPanelWidth: (width) => {
        set({ panelWidth: Math.max(280, Math.min(600, width)) });
      },

      /**
       * 清空所有数据
       */
      clearAll: () => {
        set({
          suggestions: [],
          quickActions: [],
          checklist: [],
          references: [],
          chatHistory: [],
          autocompleteOptions: [],
          showAutocomplete: false,
        });
      },

      /**
       * 生成Mock建议（私有方法）
       */
      generateMockSuggestions: (context: EditorContext, intent: WritingIntent | null): Suggestion[] => {
        const suggestions: Suggestion[] = [];

        if (intent === 'argument') {
          suggestions.push({
            id: 'sug_1',
            type: 'add_example',
            title: '添加具体例子',
            description: '当前论点需要具体例子来支撑，让观点更有说服力',
            priority: 'high',
            targetPosition: context.cursorPosition,
            actionText: '添加例子',
            icon: '💡',
            timestamp: Date.now(),
          });
        }

        if (context.wordCount > 100) {
          suggestions.push({
            id: 'sug_2',
            type: 'add_data',
            title: '补充数据支撑',
            description: '添加统计数据或研究结果，增强论证力度',
            priority: 'medium',
            targetPosition: context.cursorPosition,
            actionText: '添加数据',
            icon: '📊',
            timestamp: Date.now(),
          });
        }

        suggestions.push({
          id: 'sug_3',
          type: 'improve_style',
          title: '优化表达方式',
          description: '部分句子可以更简洁流畅',
          priority: 'low',
          targetPosition: context.cursorPosition - 50,
          actionText: '优化',
          icon: '✨',
          timestamp: Date.now(),
        });

        return suggestions;
      },

      /**
       * 生成Mock检查清单
       */
      generateMockChecklist: (context: EditorContext): ChecklistItem[] => {
        return [
          {
            id: 'check_1',
            title: '标题是否吸引人',
            description: '标题应该简洁有力，引发读者兴趣',
            status: context.wordCount > 0 ? 'passed' : 'pending',
            category: 'structure',
          },
          {
            id: 'check_2',
            title: '开头是否引人入胜',
            description: '前100字应该抓住读者注意力',
            status: context.wordCount > 100 ? 'passed' : 'warning',
            category: 'structure',
          },
          {
            id: 'check_3',
            title: '论点是否清晰',
            description: '核心观点应该明确表达',
            status: context.wordCount > 200 ? 'passed' : 'pending',
            category: 'content',
          },
          {
            id: 'check_4',
            title: '是否有足够例证',
            description: '每个论点都应该有具体例子支撑',
            status: 'warning',
            suggestion: '考虑在第3段添加一个具体例子',
            category: 'content',
          },
          {
            id: 'check_5',
            title: '语气是否一致',
            description: '全文保持统一的写作风格',
            status: 'passed',
            category: 'style',
          },
        ];
      },

      /**
       * 生成Mock参考资料
       */
      generateMockReferences: (query: string): Reference[] => {
        return [
          {
            id: 'ref_1',
            title: `${query}相关研究综述`,
            summary: '这是一篇关于该主题的权威综述文章，详细分析了当前研究现状和未来趋势...',
            source: 'Nature',
            url: 'https://example.com/paper1',
            credibility: 95,
            relevance: 88,
            timestamp: Date.now(),
          },
          {
            id: 'ref_2',
            title: `${query}的实践案例分析`,
            summary: '通过多个实际案例，展示了该理论在实践中的应用效果...',
            source: 'Harvard Business Review',
            url: 'https://example.com/article1',
            credibility: 90,
            relevance: 82,
            timestamp: Date.now(),
          },
        ];
      },

      /**
       * 生成Mock聊天回复
       */
      generateMockChatReply: (message: string): string => {
        if (message.includes('如何') || message.includes('怎么')) {
          return '根据你的问题，我建议从以下几个方面展开：\n\n1. 首先明确核心概念\n2. 然后分析具体案例\n3. 最后总结实践要点\n\n你可以点击"插入"按钮将这个框架加入到文章中。';
        }

        if (message.includes('例子')) {
          return '我为你找到一个相关的例子：\n\n例如，某科技公司通过AI技术提升了50%的工作效率。这个案例可以很好地支撑你的论点。';
        }

        return '我理解你的需求。根据当前上下文，我建议你可以从这个角度继续展开论述。需要我帮你生成一段内容吗？';
      },

      /**
       * 生成Mock自动补全
       */
      generateMockAutocomplete: (context: EditorContext): AutocompleteOption[] => {
        const lastWord = context.currentText.split(' ').pop() || '';

        if (lastWord.length < 2) return [];

        return [
          {
            id: 'auto_1',
            text: '内容创作的方式和效率',
            confidence: 0.9,
            type: 'sentence',
          },
          {
            id: 'auto_2',
            text: '整个行业的发展格局',
            confidence: 0.85,
            type: 'sentence',
          },
          {
            id: 'auto_3',
            text: '人们的工作流程',
            confidence: 0.75,
            type: 'sentence',
          },
        ];
      },
    }),
    {
      name: 'copilot-storage',
      partialize: (state) => ({
        settings: state.settings,
        isPanelVisible: state.isPanelVisible,
        panelWidth: state.panelWidth,
      }),
    }
  )
);
